﻿using System;
using System.ComponentModel;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Win.Templates.ActionContainers;
using DevExpress.XtraBars;
using DevExpress.ExpressApp;
using Hdt.TransOcean.Dal;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraEditors;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Layout.Modes;

namespace Hdt.TransOcean.Presentation
{
    public partial class OpeningBalance : DevExpress.ExpressApp.Win.Templates.XtraFormTemplateBase, ISupportClassicToRibbonTransform
    {
        private EOperation opt;
        private int isSetvalue = 0;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CheckTransformToRibbon();
        }
        protected override IModelFormState GetFormStateNode()
        {
            if (View != null)
            {
                return TemplatesHelper.GetFormStateNode(View.Id);
            }
            else
            {
                return base.GetFormStateNode();
            }
        }
        public override void SetSettings(IModelTemplate modelTemplate)
        {
            base.SetSettings(modelTemplate);
            formStateModelSynchronizerComponent.Model = GetFormStateNode();
        }
        [Obsolete("Use the DetailViewForm() constructor"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public OpeningBalance(XafApplication application) : this() { }
        public OpeningBalance()
        {
            InitializeComponent();
        }

        public OpeningBalance(EOperation operation,Invoice invoice = null)
        {
            InitializeComponent();
            this.opt = operation;

        }

        private void CreateGrid()
        {
            DataTable tb = new DataTable();
            tb.Columns.Add("closing_date");
            tb.Columns.Add("customer_code");
            tb.Columns.Add("customer_name");
            tb.Columns.Add("item_type");
            tb.Columns.Add("item_code");
            tb.Columns.Add("debt_amount");
            tb.Columns.Add("debit");
            tb.Columns.Add("credit");
            gridControlInvoiceDetail.DataSource = tb;
        }

        private void OpeningBalance_Load(object sender, EventArgs e)
        {
            Dao dao = new Dao();
            // Sales man
            gridLookUpEditSalesman.Properties.DataSource = Dao.SelectEmployee(3);
            gridLookUpEditSalesman.Properties.DisplayMember = "name";
            gridLookUpEditSalesman.Properties.ValueMember = "code";
            GridColumn colEmpCodeSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("code");
            colEmpCodeSM.VisibleIndex = 0;
            colEmpCodeSM.Width = 75;
            colEmpCodeSM.Caption = "Mã nhân viên";
            GridColumn colEmpNameSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("name");
            colEmpNameSM.VisibleIndex = 1;
            colEmpNameSM.Width = 75;
            colEmpNameSM.Caption = "Tên nhân viên";
            GridColumn colEmpPhoneSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("phone");
            colEmpPhoneSM.VisibleIndex = 2;
            colEmpPhoneSM.Width = 75;
            colEmpPhoneSM.Caption = "Số điện thoại";

            gridLookUpCustomer.DataSource = Dao.SelectCustomer();
            gridLookUpCustomer.DisplayMember = "code";
            gridLookUpCustomer.ValueMember = "code";
            GridColumn col1 = gridLookUpCustomer.View.Columns.AddField("code");
            col1.VisibleIndex = 0;
            col1.Width = 75;
            col1.Caption = "Mã khách hàng";
            GridColumn col2 = gridLookUpCustomer.View.Columns.AddField("name");
            col2.VisibleIndex = 1;
            col2.Width = 75;
            col2.Caption = "Tên khách hàng";
            GridColumn col3 = gridLookUpCustomer.View.Columns.AddField("address");
            col3.VisibleIndex = 2;
            col3.Width = 75;
            col3.Caption = "Địa chỉ";
            GridColumn col4 = gridLookUpCustomer.View.Columns.AddField("telephone");
            col4.VisibleIndex = 3;
            col4.Width = 75;
            col4.Caption = "Điện thoại";

            gridLookUpEditItemCode.DataSource = Dao.SelectItem();
            gridLookUpEditItemCode.DisplayMember = "code";
            gridLookUpEditItemCode.ValueMember = "code";
            GridColumn colCode = gridLookUpEditItemCode.View.Columns.AddField("code");
            colCode.VisibleIndex = 0;
            colCode.Width = 75;
            colCode.Caption = "Mã";
            GridColumn colName = gridLookUpEditItemCode.View.Columns.AddField("name");
            colName.VisibleIndex = 1;
            colName.Width = 75;
            colName.Caption = "Tên";

            txtOpenBalanceDate.EditValue = DateTime.Now;
            DataTable dt = new DataTable();
            dt.Columns.Add("id",typeof(Int32));
            dt.Columns.Add("Code", typeof(string));
            dt.Rows.Add(1, "Vé");
            dt.Rows.Add(2, "Tour");
            dt.Rows.Add(3, "Dịch vụ visa");
            dt.Rows.Add(4, "Vé,Tour,DV visa");
            repositoryItemLookUpItemType.DataSource = dt;
            repositoryItemLookUpItemType.DisplayMember = "Code";
            repositoryItemLookUpItemType.ValueMember = "id";
            CreateGrid();
        }

       private void hdtManageControl1_HdtNewButtonClick()
        {
            txtOpenBalanceDate.Text = DateTime.Now.ToString();
        }

        private void hdtManageControl1_HdtSaveButtonClick()
        {
            if (ValidateData() == 1)
            {
                return;
            }
            string message = "Lưu thành công!";
            Dao dao = new Dao();
            Invoice invoice = new Invoice();
            TermBeginningDebt[] invoiceDetails = null;
            int j = 0;
         
            // Add information to Invoice Deatail
            invoiceDetails = new TermBeginningDebt[gridViewInvoiceDetail.RowCount];
            for (int i = 0; i < gridViewInvoiceDetail.RowCount; i++)
            {
                DateTime OpengBalanceDate = txtOpenBalanceDate.DateTime;
                DataRow row = gridViewInvoiceDetail.GetDataRow(i);
                if (row != null)
                {
                    TermBeginningDebt item = new TermBeginningDebt();
                    item.closing_date = OpengBalanceDate;
                    item.customer_code=row["customer_code"].ToString();
                    item.credit = Decimal.Parse(Common.IIF(row["credit"].ToString() == "", 0, row["credit"]).ToString());
                    item.debit = Decimal.Parse(Common.IIF(row["debit"].ToString() == "", 0, row["debit"]).ToString());
                    item.debt_amount = Decimal.Parse(Common.IIF(row["debt_amount"].ToString() == "", 0, row["debt_amount"]).ToString());
                    if (Presentation.ValidTermBeginningDebtDetail(item))
                    {
                        invoiceDetails[j++] = item;
                    }
                }
            }// for (int i = 0; i < gridViewInvoiceDetail.RowCount; i++)

            try
            {
                    int isSuccess = Dao.InsertTermBeginningDebt(invoiceDetails);
                    if (isSuccess == 1) // Insert Success
                    {
                    }
            }
            catch (Exception e)
            {
                if (e != null)
                {
                    message = e.ToString();
                }
            }
            finally
            {
                MessageBox.Show(message, "Nhập số dư đầu kỳ - Lưu");
                gridControlInvoiceDetail.DataSource = null;
                CreateGrid();
                //txtCode.Text = this.Tag + Common.Right("00000" + (int.Parse(dao.GetCodeCurrent(this.Name, this.Tag.ToString())) + 1).ToString(), lengthCode);
                txtTotalAmount.Text = "0";
                txtTotalAmountUSD.Text = "0";
            }
        }

        private void hdtManageControl1_HdtEditButtonClick()
        {

        }

        private void hdtManageControl1_HdtDeleteButtonClick()
        {

        }

        private void hdtManageControl1_HdtCloseButtonClick()
        {

        }

        private void hdtManageControl1_HdtExportButtonClick()
        {

        }

        private void hdtManageControl1_HdtImportButtonClick()
        {

        }

        //private void gridLookUpEditCustomer_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        //{
        //    DevExpress.XtraEditors.GridLookUpEdit edit = sender as DevExpress.XtraEditors.GridLookUpEdit;
        //    Customer customer = edit.Properties.View.GetRow(edit.Properties.View.FocusedRowHandle) as Customer;

        //    if (customer != null)
        //    {
        //        txtCustomerAddress.Text = customer.address.ToString();
        //        txtCustomerPhone.Text = customer.telephone.ToString();
        //        txtCustomerName.Text = customer.name.ToString();
        //    }            
        //}

        void GetItemPrice(string journeyCode, string airlineCode)
        {
            Dao dao = new Dao();
            Item item = dao.SelectItemByJourneyAndAirline(journeyCode,airlineCode);
            if (item == null)
            {
                MessageBox.Show("Chọn lại hành trình và hãng hàng không");
                return;
            }
            gridViewInvoiceDetail.SetRowCellValue(gridViewInvoiceDetail.FocusedRowHandle,"sale_price", item.sale_price);

        }

        public int ValidateData()
        {
            int flagError = 0;
            return flagError;
        }

        public void SetTotalAmount()
        {
            decimal totalAmount = 0;
            int dataRowCount = gridViewInvoiceDetail.RowCount;
            for (int i = 0; i < dataRowCount; i++)
            {
                DataRow row = gridViewInvoiceDetail.GetDataRow(i);
                if (row != null)
                {
                    totalAmount += decimal.Parse(Common.IIF(row["debt_amount"].ToString()=="","0",row["debt_amount"].ToString()).ToString());
                }
            }
            txtTotalAmount.Text  = totalAmount.ToString();
        }

        private void gridViewInvoiceDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            Dao dao = new Dao();
            switch(e.Column.FieldName.ToString())
            {
                case "customer_code":
                     string customerCode = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "customer_code").ToString();
                     if (Dao.SelectCustomer(customerCode).Count > 0)
                     {
                        Customer cus = Dao.SelectCustomer(customerCode)[0];
                        gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "customer_name", cus.name);
                     }

                    break;
                case "customer_name":
                    break;
                case "item_type":
                    int itemType =int.Parse( gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "item_type").ToString());
                    if (Dao.SelectItem(itemType).Count > 0)
                    {
                        gridLookUpEditItemCode.DataSource = Dao.SelectItem(itemType);
                        gridLookUpEditItemCode.DisplayMember = "code";
                        gridLookUpEditItemCode.ValueMember = "code";
                    }
                    break;
                case "item_code":
                    break;
                case "debt_amount":
                    break;

                case "debit":
                    decimal credit = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "credit").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "credit")).ToString());
                    decimal debit = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "debit").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "debit")).ToString());
                    if (credit != 0 && isSetvalue==0)
                    {
                        isSetvalue = 1;
                        MessageBox.Show("chỉ có số dư bên Nợ hoặc bên Có", "Thông báo");
                        gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "debit", 0);
                        isSetvalue = 0;
                        return;
                    }
                    else
                        if (debit < 0 && isSetvalue == 0)
                        {
                            isSetvalue = 1;
                            MessageBox.Show("số tiền phải >=0");
                            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "debit", 0);
                            isSetvalue = 0;
                        }

                    break;

                case "credit":
                    debit = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "debit").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "debit")).ToString());
                    credit = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "credit").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "credit")).ToString());
                    if (debit != 0 && isSetvalue == 0 )
                    {
                        //MessageBox.Show("chỉ có số dư bên Nợ hoặc bên Có", "Thông báo");
                        //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "credit", 0);
                        isSetvalue = 1;
                       // gridViewInvoiceDetail.SetFocusedValue(0);
                        MessageBox.Show("chỉ có số dư bên Nợ hoặc bên Có", "Thông báo");
                        gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "credit", 0);
                        isSetvalue =0;
                        return;
                    }
                    else
                        if (credit < 0 && isSetvalue == 0)
                        {
                            isSetvalue = 1;
                            MessageBox.Show("số tiền phải >=0");
                            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "credit", 0);
                            isSetvalue = 0;
                        }
                    break;
            }
            
        }

        private void gridViewInvoiceDetail_RowCountChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }

        private void gridViewInvoiceDetail_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SetTotalAmount();
        }

        private void gridViewInvoiceDetail_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            //e.RowHandle 
            gridViewInvoiceDetail.SetRowCellValue(gridViewInvoiceDetail.FocusedRowHandle, "depart_date", DateTime.Now );
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "return_date", DateTime.Now);
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "currency_code", "VND");
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "rate", 1);
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "quantity", 1);
        }
        
        #region sub Menu
        class RowInfo
        {
            public RowInfo(GridView view, int rowHandle)
            {
                this.RowHandle = rowHandle;
                this.View = view;
            }
            public GridView View;
            public int RowHandle;
        }

        void OnAddRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.AddNewRow();
        }
        DXMenuItem CreateRowMenuAddRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Thêm dòng", new EventHandler(OnAddRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);
            return itemMenu;
        }

        DXMenuCheckItem CreateMergingEnabledMenuItem(GridView view, int rowHandle)
        {
            DXMenuCheckItem checkItem = new DXMenuCheckItem("&Merging Enabled",
            view.OptionsView.AllowCellMerge, null, new EventHandler(OnMergingEnabledClick));
            checkItem.Tag = new RowInfo(view, rowHandle);
            return checkItem;
        }

        //The handler for the MergingEnabled menu item
        void OnMergingEnabledClick(object sender, EventArgs e)
        {
            DXMenuCheckItem item = sender as DXMenuCheckItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.OptionsView.AllowCellMerge = item.Checked;
        }

        // Create a submenu with a single DeleteRow item.
        DXMenuItem CreateRowMenuDeleteRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Xoá dòng", new EventHandler(OnDeleteRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);//"adadad";       
            return itemMenu;
        }

        ////The handler for the DeleteRow menu item
        void OnDeleteRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.DeleteRow(info.RowHandle);
        }
        #endregion

        private void gridViewInvoiceDetail_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            GridView view = sender as GridView;
            // Check whether a row is right-clicked.
            if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Row)
            {
                int rowHandle = e.HitInfo.RowHandle;
                // Delete existing menu items, if any.
                e.Menu.Items.Clear();
                // Add a submenu with a single menu item.
                e.Menu.Items.Add(CreateRowMenuAddRow(view, rowHandle));
                e.Menu.Items.Add(CreateRowMenuDeleteRow(view, rowHandle));
                // Add a check menu item.
                //DXMenuItem item = CreateMergingEnabledMenuItem(view, rowHandle);
                //item.BeginGroup = true;
                //e.Menu.Items.Add(item);
            }
        }

        
    }
}
